#-*- encoding: utf-8 -*-

"""
Yahoo Finance API
YFA接口基本常熟和方法定义

"""

import re

# 股票数据接口参数键值定义

KEY_IDS = "s"
KEY_PROPERTIES = "f"
KEY_RT_FORMAT = "e"

#KEY_IDS = "s"
KEY_FROMDATE_YEAR = "c"
KEY_FROMDATE_MONTH = "a"
KEY_FROMDATE_DAY = "b"
KEY_TODATE_YEAR = "f"
KEY_TODATE_MONTH = "d"
KEY_TODATE_DAY = "e"
KEY_INTERVAL = "g"

KEY_HIS_FORMAT = "ignore"

# 参数取值
VALUE_INTERVAL_DAILY = "d"
VALUE_INTERVAL_WEEKLY = "w"
VALUE_INTERVAL_MONTHLY = "m"

VALUE_FORMAT_CSV = ".csv"

# 其它常量定义
BASE_HIS_URL = "http://ichart.yahoo.com/table.csv"
BASE_RT_URL = "http://download.finance.yahoo.com/d/quotes.csv"

MARKET_CODES = {"SHANGHAI": "ss", "SHENZHEN": "sz"}

QUOTE_SYMBOL = "Symbol"


def checkStockCode(code):
    """
    检查并按照YFA接口处理股票代码，本方法仅针对上海和深圳股市的代码进行整理，主要根据
    两个市场的代码规则进行判断，如果仅有代码，需要添加YFA代码要求的市场后缀；如果已经
    有后缀则直接返回；如果非两个市场的代码也直接返回
    """
    #print("check stock code:", code)
    if code==None or code=="":
        return
    if len(code)!=6:
        return code
    if code.endswith(".ss") or code.endswith(".sz"):
        return code

    pss = re.compile("^(600|601|900)\d{3}$")
    m = pss.match(code)
    #print("check ss", m)
    if m!=None:
        return code+".ss"
    
    psz = re.compile("^(000|002|300)\d{3}$")
    m = psz.match(code)
    #print("check sz", m)
    if m!=None:
        return code+".sz"

    return code

def createIds(ids):
    """ ids maybe string or list, create url paramter ids from it """
    ret = ""
    if type(ids) is str:
        #print("is str")
        if ids!=None and ids!="":
            vals = ids.split(",")
            for id in vals:
                if id==None or id=="":
                    continue
                if len(ret)>0:
                    ret = ret+","
                ret = ret + checkStockCode(id.strip())
    elif type(ids) is list:
        #print("is list")
        for id in ids:
            if id==None and id=="":
                continue
            if len(ret)>0:
                ret = ret+","
            ret = ret + checkStockCode(id.strip())
            #print(ret)
    else:
        #print("...", type(ids))
        pass

    return ret

def checkStringValue(val):
    """
    对输入值进行检查，针对csv格式的字符串数据，其他数据直接返回；
    如果有引号包含在数据中，则仅取引号内的数值返回
    """
    if val==None or val=="":
        return val

    if type(val)!=str:
        return val

    v = val.strip()
    start = v.find('"')
    #print(v, start)
    if start<0:
        return val;
    end = v.rfind('"')
    ''' 这是一个注释 '''
    #print(v, end)
    if end<0:
        return val;
    return v[int(start)+1: int(end)]
